import React, { Component } from 'react';
import {
	Table,
	Button,
	// Select,
	Input,
	Row,
	Col,
	Pagination, ConfigProvider,
	// message
} from 'antd';
import styles from './index.module.scss';
import { getSourceTables, getSourceTableSchema, getSourceTableData } from 'src/services/DataManage/index';
import zhCN from 'antd/es/locale/zh_CN';

interface Iprops {
	location:any
	history:any
}

class DataPreview extends Component<Iprops,any> {
	state = {
		kw: '',
		rowId: '',
		dbType: '',
		loading: true,
		tableName: '',
		originalData: [],
		tableData: [],

		columns: [],
		sourceData: [],
		dbId: '',

		total: 1,
		page: 1,
		pageSize: 10,
		
	};
	

	//处理搜索框
	handleSearchInput = e => {
		this.setState( { kw: e.target.value } );
	}

	//列内搜索
	handleSearchEnter = () => {
		console.log( `执行搜索 ======${  this.state.kw}` );
		// record[dataIndex]
		// 		? record[dataIndex].toString().toLowerCase().includes(value.toLowerCase())
		// 		: ''
		if( this.state.kw ) {
			//筛选数据
			const data = this.state.originalData.filter( item => item['name'].toString().toLowerCase().includes( this.state.kw.toLowerCase() ) );
			//更新数据
			this.setState( { tableData: data } );
		}else {
			//将原始数据赋值给显示的table数据
			this.setState( { tableData: this.state.originalData } );
		}
		
	}

	//数据库选择
	handlSelectChang = value => {
		console.log( value );
		//	请求数据表数据

		//设置表数据
		// this.setState( {
		// 	tableData: data ,
		// 	originalData: data,
		// } );
	}

	// 选中行
	onClickRow = ( record ) => {
		return {
			onClick: () => {
				// console.log( record );
				this.setState( {
					rowId: record.key,
					tableName: record.name,
					page: 1,
					total: 1,
				},
				 () => {
					this.tableAllData();
				}
				);
			},
			// onContextMenu: event => {},
			// onMouseEnter: event => {}, // 鼠标移入行
			// onMouseLeave: event => {},
		};
	}
	
	//设置类名
	setRowClassName = ( record ) => {
		return record.key === this.state.rowId ? `${styles.clickRowStyl}` : '';
	}
	
	//翻页
	PageChange = page => {
		this.setState( { page },() => {
			this.tablePreviewData( { 'data': {
				'dbId': this.state.dbId,
				'page': page,
				'size': this.state.pageSize,
				'tableName': this.state.tableName
			} } );
		} );
		
	}
	
	//切换pagesize
	handlePageSizeChange =  ( page,pageSize ) => {
		this.setState( {
			pageSize: pageSize,
		} , () => {
			//获取table sourcedata
			this.tablePreviewData( { 'data': {
				'dbId': this.state.dbId,
				'page': this.state.page,
				'size': this.state.pageSize,
				'tableName': this.state.tableName
			} } );
		} );
	}

	//返回按钮
	handleReturn = () => {
		this.props.history.push( '/dataManage/dataConnect' );
	}
	
	//获取侧边栏数据表选项数据
	tablesData = async params => {
		const info = await getSourceTables( params );
		if ( info.data.success ) {
			let data = info.data.data.map( ( item,index ) => {return { key: index,name: item }; } );
			this.setState( {
				tableData: data ,
				originalData: data,
				rowId: data[0] ? data[0].key : '',
				tableName: data[0] ? data[0].name : ''
				
			},async () => {
				this.tableAllData();
			} );
		}
	}
	
	//获取表数据字段
	tableSchema = async params => {
		const info = await getSourceTableSchema( params );
		if ( info.data.success ) {
			this.setState( {
				columns: info.data.data.columns.map( item => {
					return {
						title: item.desc,
						dataIndex: item.name,
						key: item.name,
						// ellipsis: true,
					};
				} )
			} );
			
		}
	}
	
	//获取表预览数据
	tablePreviewData = async params => {
		this.setState( { loading: true } );
		// if( params.tableName ) {
		const info = await getSourceTableData( params );
		if ( info.data&&info.data.success ) {
			this.setState( {
				total: info.data.data.total,
				sourceData: info.data.data.rows,
				loading: false
			} );
		}
		// }else {
		// 	message.warning( '当前连接无表数据，请联系数据库管理员' );
		// 	this.setState( {
		// 		loading: false
		// 	} );
		// }
		
	}
	
	//获取表头数据和表数据
	tableAllData = () => {
		//获取 预览表 表头数据
		let data = { data: { 'dbId': this.state.dbId, 
			'tableName': this.state.tableName } };
		//当表名称存在（有权限时）是，请求预览数据
		if( this.state.tableName ) {
			this.tableSchema( data );
			//获取 预览表数据
			let previewData = { 'data': {
				'dbId': this.state.dbId,
				'page': this.state.page,
				'size': this.state.pageSize,
				'tableName': this.state.tableName
			}, };
			this.tablePreviewData( previewData );
		}
		
	}

	//生命周期函数
	componentDidMount(): void {
		let tmp  = { id: '' ,typeName: '' };
		const mdata = this.props.location.query;
		if ( mdata ) {
			//状态保持，刷新后不丢失
			window.sessionStorage.setItem( 'dbId',mdata.id );
			window.sessionStorage.setItem( 'typeName',mdata.typeName );
			tmp['id'] = mdata.id;
			tmp['typeName'] = mdata.typeName;
		}else {
			tmp['id'] = window.sessionStorage.getItem( 'dbId' );
			tmp['typeName'] = window.sessionStorage.getItem( 'typeName' );
		}
		//获取表集合数据并
		this.setState( { dbId: tmp.id, dbType: tmp.typeName },() => {this.tablesData( { data: this.state.dbId } );} );
	}
	
	componentWillUnmount(): void {
		window.sessionStorage.removeItem( 'dbId' );
	}

	render() {
		const columns = [
			{
				title: 'Name',
				dataIndex: 'name',
				key: 'name',
				ellipsis: true,
			}
		];
		
		
		return (
			// 侧边选项栏
			<div className={styles.content}>
				<div className={styles.slider}>
					{/*<Row><h3>数据库选择</h3></Row>*/}
					{/*<Select defaultValue="lucy" style={{ width: 180 }} onChange={this.handlSelectChang}>*/}
					{/*	<Select.Option value="jack">Jack</Select.Option>*/}
					{/*	<Select.Option value="lucy">Lucy</Select.Option>*/}
					{/*</Select>*/}
					<Row><h3>数据表</h3></Row>
					<Input placeholder="请输入关键词回车搜索" onChange={this.handleSearchInput} onPressEnter={this.handleSearchEnter}/>
					<Table  columns={columns}
						key="slideData"
						rowKey={record => record.key}
						dataSource={this.state.tableData}
						pagination={false}
						// rowSelection={{ type: 'radio',hideSelectAll: true }}
						scroll={{ y: 735 }}
						onRow={this.onClickRow}
						rowClassName={this.setRowClassName}
						showHeader={false}/>
				</div>
				{/*数据展示*/}
				<div className={styles.tableContent}>
					<Row justify={'end'} gutter={24} className={styles.row} >
						{
							this.state.dbType.indexOf( 'hive' ) !== -1?<Col pull={2}>hive仅显示10条记录</Col>:null
						}
						<Col pull={1}>
							<ConfigProvider locale={zhCN}>
								<Pagination showQuickJumper
												  showSizeChanger
												  defaultCurrent={1}
												  current={this.state.page}
												  total={this.state.total}
												  onShowSizeChange={this.handlePageSizeChange}
												  onChange={this.PageChange} />
							</ConfigProvider>
						</Col>
						<Col pull={1}><Button type="primary"
											  onClick={this.handleReturn}>返回</Button>
						</Col>
					</Row>
					<Table dataSource={this.state.sourceData}
						   loading={this.state.loading}
						   rowKey={record => record.key}
						   scroll={{ x: '100%' }}
						   className={styles.table}
							   size={'small'}
						   pagination={false}
						   columns={this.state.columns}>
					</Table>
				</div>
			</div>
		);
	}
}

export default DataPreview;